--基于WWW 封装的Http访问接口
module("NetWork.NetHttp", package.seeall)

local json = require("cjson")

NetHttp = {}
NetHttp.token=nil

--发起Http请求，这个调用是异步的
function SendRequest(url, fun, wwwfrom)
    function coroFun()
        
        local www = nil
        if nil == wwwfrom then
            www = UnityEngine.WWW(url)
        else
            www = UnityEngine.WWW(url, wwwfrom)
        end
        coroutine.www(www)
        if nil ~= www.error then
            print("error： " .. www.error)
            Debug.LogErrorEx("error： " .. www.error)
            
            -- WebGL中的CORS错误处理
            if string.find(www.error, "CORS") or string.find(www.error, "Access-Control-Allow-Origin") then
                Debug.LogErrorEx("CORS错误：服务器未配置跨域访问，请检查服务器配置")
                -- 可以在这里添加备用逻辑
            end
            
            fun(false, nil) --是否成功，返回的数据
            return
        end
        local strdata = tolua.tolstring(www.bytes)
        if nil ~= fun then
            fun(true, json.decode(strdata))
            --是否成功，返回的数据
        end
    end

    coroutine.start(coroFun)
end

--发起POST请求，这个调用是异步的
function SendPostRequest(url, fun, postData)
	function coroFun(strdata)
        local jsondata = json.decode(tolua.tolstring(strdata))
     
        
        if jsondata.code~=200 then
           
            fun(false, jsondata) --是否成功，返回的数据
            return
		else
			if nil ~= fun then
				fun(true, jsondata)
				--是否成功，返回的数据
			end
        end
    end
	NetHelper.SendHttpRequestByASyn(require("Module.ConfigModule").ConfigModule.SessionUrl..url,postData,coroFun)
     
end

--发起POST请求，这个调用是异步的
function SendPostRequest_token(url, fun, postData)
	function coroFun(strdata)
        local jsondata = json.decode(tolua.tolstring(strdata))
     
        
        if jsondata.code~=200 then
           
            fun(false, jsondata) --是否成功，返回的数据
            return
		else
			if nil ~= fun then
				fun(true, jsondata)
				--是否成功，返回的数据
			end
        end
    end
	NetHelper.PostRequest_token(require("Module.ConfigModule").ConfigModule.SessionUrl..url,postData,coroFun,NetHttp.token)
     
end

--发起POST请求，这个调用是异步的
function SendGetRequest(url, fun)
	function coroFun(strdata)
        local jsondata = json.decode(tolua.tolstring(strdata))
     
        
        if jsondata.code~=200 then
           
            fun(false, jsondata) --是否成功，返回的数据
            return
		else
			if nil ~= fun then
				fun(true, jsondata)
				--是否成功，返回的数据
			end
        end
    end
    if NetHttp.token ==nil then
       print("token为空")
        
    end
   
   
  
	NetHelper.SendGetRequestSendByASyn(require("Module.ConfigModule").ConfigModule.SessionUrl..url,NetHttp.token,coroFun)
     
end

--发起一个WWW请求，回调函数 callBack 会传入一个 www 对象
function WWW(url, callBack, wwwfrom)
    function coroFun()
        local www = nil
        if nil == wwwfrom then
            www = UnityEngine.WWW(url)
        else
            www = UnityEngine.WWW(url, wwwfrom)
        end
        coroutine.www(www)
        local isOk = true
        if nil ~= www.error then
            Debug.log("error： " .. www.error)
            Debug.log("error url：" .. www.url)
            isOk = false
            www:Dispose()
            www = nil
        end
        if callBack then
            if type(callBack) == "function" then
                callBack(isOk, www) --是否成功，返回的数据
            end
        end
        if nil ~= www then
            www:Dispose()
        end
    end

    coroutine.start(coroFun)
end

function GetUrlBypf(picName)
    -- local a = string.find(picName, "fb_")

    -- if a == 1 then
    --     local b = string.gsub(picName, "fb_", "")
    --     return "http://graph.facebook.com/" .. b .. "/picture?type=large"
    -- else
    --     return "http://headimg.kkpker.com:5581/headimage/img/" .. picName .. ".png"
    -- end
    return "http://45.204.222.210:8080/gameIcon/" .. picName
end

--发起一个WWW请求图片下载，如果图片已经下载过，则从缓存里面读取，如果没有下载过，则从网上下载
function WWWTexture(picName, callBack)
    --local url = "http://headimg.kkpker.com:5581/headimage/img/"..picName..".png"
    local url = GetUrlBypf(picName)
    local urlHash = PlatformTool.Instance:GetStringHashCode(url)
    local filePath = UnityEngine.Application.persistentDataPath .. "/" .. urlHash
    if System.IO.File.Exists(filePath) then
        
        local localPath = "file:///" .. filePath
        local WWW = require("NetWork.NetHttp").WWW
        WWW(localPath, callBack)
    else
        
        local WWW = require("NetWork.NetHttp").WWW
        function callBackWarp(isok, wwwrtn)
            if isok then
                image = wwwrtn.texture
                --local pngData = image:EncodeToPNG()
                local pngData = UIHelper.GetTexturePNG(image)
                System.IO.File.WriteAllBytes(filePath, pngData)
            end

            if callBack then
                if type(callBack) == "function" then
                    callBack(isok, wwwrtn)
                end
            end
        end

        WWW(url, callBackWarp)
    end
end

-----下载新头像

function WWWNewdownTexture(userId, callBack)
    --local url = "http://headimg.kkpker.com:5581/headimage/img/"..userId..".png"
    local url = GetUrlBypf(userId)
    --local url = "http://headimage.jinlongguolv.com:3319/headimage/img/"..userId..".png"

    Debug.LogErrorEx("userIdurl---------------------" .. userId)
    --local urlHash = url

    -- if System.IO.File.Exists(UnityEngine.Application.persistentDataPath .. "/" .. userId) then

    -- 	local localPath = "file:///"..UnityEngine.Application.persistentDataPath .. "/" .. userId
    -- 	local WWW = require("NetWork.NetHttp").WWW
    -- 	WWW(localPath, callBack)
    -- else

    -- 	local WWW = require("NetWork.NetHttp").WWW
    -- 	function callBackWarp(isok, wwwrtn)
    -- 		if isok then
    -- 			image = wwwrtn.texture
    -- 			local pngData = image:EncodeToPNG()
    -- 			System.IO.File.WriteAllBytes(UnityEngine.Application.persistentDataPath .. "/" .. userId, pngData)
    -- 		end

    -- 		if callBack then
    -- 			if type(callBack) == "function" then
    -- 				callBack(isok, wwwrtn)
    -- 			end
    -- 		end
    -- 	end
    -- 	WWW(url, callBackWarp)
    -- end


    local WWW = require("NetWork.NetHttp").WWW
    function callBackWarp(isok, wwwrtn)
        if isok then
            image = wwwrtn.texture
            --local pngData = image:EncodeToPNG()
            local pngData = UIHelper.GetTexturePNG(image)
            --local pngData = image:EncodeToPNG()
            Debug.LogErrorEx("url---------------------" .. url)
            System.IO.File.WriteAllBytes(UnityEngine.Application.persistentDataPath .. "/" .. userId, pngData)
        end

        if callBack then
            if type(callBack) == "function" then
                callBack(isok, wwwrtn)
            end
        end
    end

    WWW(url, callBackWarp)
end

--上传头像
-- function WWWUpdataTexture(bytes,userid)
function WWWUpdataTexture(bytes)
    local WWW = require("NetWork.NetHttp").WWW
    Debug.LogErrorEx("打印字节------" .. #bytes)
    --local userid = userid
    -- local urlHash = url

    --local url = "http://43.255.29.231:2319/headimage/"
    --local url = "http://192.168.1.17:18080/headimage/img/"
    local url = "http://headimg.kkpker.com:5581/headimage/img/"


    wwwfrom = UnityEngine.WWWForm()

    -- wwwfrom:AddField("userid", userid)
    -- wwwfrom.AddField("info", infostr);
    wwwfrom.AddBinaryData("headimage", bytes, "8888.png")

    WWW(url, nil, wwwfrom)
end

------
function WWWdownchoujiangTexture(url, callBack)
    --local url = "http://image.luckypokergo.com:2319/headimage/img/"..userId..".png"
    local WWW = require("NetWork.NetHttp").WWW
    function callBackWarp(isok, wwwrtn)
        if isok then
        end

        if callBack then
            if type(callBack) == "function" then
                callBack(isok, wwwrtn)
            end
        end
    end

    WWW(url, callBackWarp)
end
